<template>
	<view>
		<!-- <u-navbar :is-back="true" :is-fixed="true" title="新增产品"></u-navbar> -->
		<scroll-view scroll-y scroll-with-animation style="height: calc(100vh - 50px);" :show-scrollbar="false">
			<view style=" background-color:#EFEDE9;">
				<view class="pl-2 pr-2 font-14 lineHight-40 font-weight-bold">服务信息</view>
			</view>
			<view class="">
				<u-form :model="form" ref="uForm">
					<u-form-item :required="true" label-width="230" label="产品/服务名称" prop="productServeName"
						style="padding-left: 10px; padding-right: 10px;">
						<u-input v-model="form.productServeName" placeholder="请输入产品/服务名称" />
					</u-form-item>
					<u-form-item :required="true" label-width="230" label="服务商名称" prop="serviceName"
						style="padding-left: 10px; padding-right: 10px;">
						<u-input :disabled="true" v-model="enterpriseName" placeholder="请输入服务商名称" />
					</u-form-item>
					<u-form-item :required="true" label-width="230" label="服务价格(元)" prop="servicePrice"
						style="padding-left: 10px; padding-right: 10px;">
						<u-input v-model="form.servicePrice" placeholder="￥" />
					</u-form-item>
					<u-form-item :required="true" label-width="230" label="服务介绍" prop="serviceIntroduction"
						style="padding-left: 10px; padding-right: 10px;">
						<u-input type="textarea" height="100" placeholder="请输入服务介绍"
							v-model="form.serviceIntroduction" />
					</u-form-item>
					<view class="text-right text-BEBFE8 pr-2">({{ wordCount }} / {{maxCharacters }})</view>
					<u-form-item :required="true" label-width="230" label="服务介绍详情"
						style="padding-left: 10px; padding-right: 10px;">
						<u-upload ref="uUpload" :max-size="4 * 1024 * 1024" :form-data="{'biz':'temp'}" :header="header"
							@on-success="uploadSuccess" :action="getUploadUrl()" max-count="5"></u-upload>
					</u-form-item>
					<view class="font-12 text-FF0000 pl-1 pb-2">图片大小限制不能超过4MB,最多能上传五张图片</view>
					<!-- 	<u-form-item :required="true" label-width="230" label="服务流程"  style="padding-left: 10px; padding-right: 10px;">
				 		<u-input type="textarea" height="50" v-model="form.serviceFlow" />
				 	</u-form-item> -->
					<!-- <u-form-item :required="true" label-width="230" label="售后服务"  style="padding-left: 10px; padding-right: 10px;">
				 		<u-input type="textarea" height="50" v-model="form.serviceInform" />
				 	</u-form-item> -->
					<view style=" background-color:#EFEDE9; ">
						<view class="pl-2 pr-2 font-14 lineHight-40 font-weight-bold">上/下架状态</view>
					</view>
					<u-form-item :required="true" label-width="230" label="上/下架状态"
						style="padding-left: 10px; padding-right: 10px;">
						<u-input v-model="form.productStatusText" type="select" :border="false"
							@click="showList = true" />
						<u-action-sheet :list="actionSheetList" v-model="showList"
							@click="actionSheetCallback"></u-action-sheet>
					</u-form-item>
				</u-form>
			</view>
			<ferrButton title="确认新增产品" @click="addProduct()"></ferrButton>
		</scroll-view>
	</view>
</template>

<script>
	import $H from "@/common/free-lib/request.js";
	import $U from '@/common/free-lib/util.js';
	import ferrButton from "@/components/free-ui/ferr-button.vue";
	import calendar from "@/uni_modules/uni-calendar/components/uni-calendar/uni-calendar.vue"
	export default {
		components: {
			ferrButton,
			calendar
		},

		data() {
			return {
				rules: {
					productServeName: [{
							required: true,
							message: '产品/服务名称不能为空',
							trigger: ['change', 'blur'],
						}

					],
					serviceIntroduction: [{
						required: true,
						message: '服务介绍不能为空',
						trigger: ['change', 'blur'],
					}],
					servicePrice: [{
							required: true,
							message: '价格不能为空',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								// 允许数字和最多两位小数，并且不小于零
								const reg = /^(0|[1-9]\d*)(\.\d{1,2})?$/;
								if (!reg.test(value)) {
									callback(new Error('请输入非负数字，可以有最多两位小数'));
								} else {
									callback();
								}
							},
							trigger: ['change', 'blur'],
						}
					]

				},
				form: {
					productServeName: "",
					serviceName: '',
					serviceIntroduction: '',
					servicePrice: '',
					serviceFlow: '',
					serviceInform: '',
					productStatus: '',
					productStatusText: '',
					updateTime: '',
				},
				value: '',
				showList: false,
				border: true,
				labelStyle: {
					paddingLeft: '13px'
				},
				actionSheetList: [{
						text: '上架',
						status: 1
					},
					{
						text: '下架',
						status: 0
					}
				],
				header: $H.getTokenHeader(),
				enterpriseName: $U.getStorage("enterpriseName"),
				maxCharacters: 200,
			}
		},
		onReady() {
			this.form.productStatus = this.actionSheetList[0].status;
			this.form.productStatusText = this.actionSheetList[0].text;
			this.$refs.uForm.setRules(this.rules);
		},
		computed:{
		  wordCount() {
		  	// 安全性检查，避免访问未定义的属性
		  	if (this.form.serviceIntroduction && typeof this.form.serviceIntroduction === 'string') {
		  		return this.form.serviceIntroduction.length;
		  	} else {
		  		return 0;
		  	}
		  }	
		},
		methods: {
			actionSheetCallback(index) {
				this.form.productStatus = this.actionSheetList[index].status;
				this.form.productStatusText = this.actionSheetList[index].text;
			},
			getUploadUrl(url) {
				return $H.getFullUrl('sys/common/upload');
			},
			uploadSuccess(data, index, lists, name) {
				if (data.success) {
					uni.showToast({
						title: '图片上传成功',
						icon: 'none'
					});
				} else {
					uni.showToast({
						title: data.message || '图片上传失败',
						icon: 'none'
					});
				}
			},
			addProduct() {
				let files = [];
				files = this.$refs.uUpload.lists.filter(val => {
					return val.progress == 100;
				})
				if (files.length == 0) {
					uni.showToast({
						title: '请上传文件',
						icon: 'none'
					});
					return;
				}
				this.$refs.uForm.validate(valid => {
					if (valid) {
						uni.showLoading({
							title: '加载中'
						});

						const upperUserId = $U.getStorage("id");
						if (!upperUserId) {
							uni.showToast({
								title: "请重新登录",
								icon: "error",
							});
							uni.hideLoading();
							return;
						}
						// Collect all file URLs and join them with commas
						const fileUrls = files.map(file => file.response.message).join(',');
						$H.post(
							"/upper/upperMarketProduct/upper/add", {
								productServeName: this.form.productServeName,
								serviceName: this.enterpriseName,
								serviceIntroduction: this.form.serviceIntroduction,
								servicePrice: this.form.servicePrice,
								serviceFlow: this.form.serviceFlow,
								serviceInform: this.form.serviceInform,
								productStatus: this.form.productStatus,
								upperUserId: upperUserId,
								serviceIntroductionUrl: fileUrls // Join URLs with commas
							}, {}
						).then((res) => {
							if (res.code === 500) {
								uni.showToast({
									title: res.message || "服务价格不能小于0",
									icon: "none",
									duration: 4000
								});
							} else if (res.success) {
								uni.showToast({
									title: res.message || "添加成功",
									icon: "none",
									duration: 4000
								});
								setTimeout(() => {
									uni.navigateBack({
										delta: 1
									});
								}, 4000);
							} else {
								uni.showToast({
									title: res.message || "添加失败",
									icon: "none",
									duration: 4000
								});
							}
							uni.hideLoading();
						}).catch(error => {
							console.error('请求出错', error); // 处理任何错误
							uni.hideLoading();
						})
					} else {
						console.log('验证失败');
					}
				});
			}
		}
	}
</script>

<style>
</style>